import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Button, Table } from 'antd';

export default function Publishcomponent(props) {
  let { username } = JSON.parse(localStorage.getItem('token'));
  const [dataSource, setDataSource] = useState([]);
  const typeList = ['', '发布', '下线', '删除'];
  let { type } = props;
    useEffect(()=>{
      axios({
        url:`/news?author=${username}&publishState=${type}&_expand=category&auditState=2`
      }).then(res =>{
        console.log(res.data);
        setDataSource(res.data)
      })
    },[username, type])
    const columns = [
      {
        title: '标题',
        dataIndex: 'title',
        render: (title, item)=>{
          return(
            <a href={`/sandbox/news/preview/${item.id}`}>{title}</a>
          )
        }
      },
      {
        title: '作者',
        dataIndex: 'author',
      },
      {
        title: '分类',
        dataIndex: 'category',
        render:(category)=> {
          return category.title;
        }
      },
      {
        title: '操作',
        render:(item)=> {
          return (
              <Button danger={type==='2'? true : false } type='primary' onClick={()=>{
                handleclick(type, item);
              }}>{typeList[type]}</Button>
          )
      }
      },
    ];

    const handleclick = (type, item) =>{
      setDataSource(dataSource.filter( data => data.id !== item.id ));
      if(type === '1'){
        axios.patch(`/news/${item.id}`,{publishState: 2});
      }
      else if(type === '2'){
        axios.patch(`/news/${item.id}`,{publishState: 3});
      }
      else
        axios.delete(`/news/${item.id}`);
    }

  return (
    <Table 
      dataSource={dataSource} 
      columns={columns} 
      rowKey={item => item.id}
      pagination= {{
        pageSize:5
      }}/>
  )
}
